package com.bird.component.lang.common.response

import com.bird.component.lang.common.exception.ServiceException
import com.bird.component.lang.common.exception.StatusInfo


val DEFAULT_SUCCESS_MSG = StatusInfo.OK.message()
val DEFAULT_SUCCESS_STATUS = StatusInfo.OK.status()
val DEFAULT_FAIL_MSG = StatusInfo.BUSINESS_ERROR.message()
val DEFAULT_FAIL_STATUS = StatusInfo.BUSINESS_ERROR.status()

/**
 * 包装成功
 */
fun <T> success(
    status: Int = DEFAULT_SUCCESS_STATUS,
    msg: String = DEFAULT_SUCCESS_MSG,
    result: (() -> T?)? = null
): JSONResponse<T> {
    return build(msg = msg, status, result?.let { it() })
}
/**
 * build 返回包装类型
 */
fun <T> build(msg: String, status: Int, result: T?): JSONResponse<T> {
    return JSONResponse(result, status, System.currentTimeMillis(), msg)
}

/**
 * 包装失败
 */
fun <T> fail(status: Int? = null, msg: String? = null, result: (() -> T?)? = null): JSONResponse<T> {
    return build(
        msg ?: DEFAULT_FAIL_MSG,
        status ?: DEFAULT_FAIL_STATUS,
        result?.let { it() }
    )
}

/**
 * 如果返回值不为成功，则抛出定义的异常
 */
fun <T> JSONResponse<T>.takeOrThrow(errorDeal: (JSONResponse<T>) -> ServiceException): T? {
    if (status != StatusInfo.OK.status()) {
        throw errorDeal(this)
    }
    return result
}

/**
 * 获取返回值，并包装上层抛出的错误抛出
 */
fun <T> JSONResponse<T>.take(): T? {
    return takeOrThrow{ ServiceException(it.msg, it.status) }
}

